package top.kaoshanji.p2ch10b;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 代码清单-p2ch10b-182页a：过滤器分发器
 * @author kaoshanji
 * ^_^
 * create time 2025/4/8 18:13
 */
@WebFilter(filterName = "DispatcherFilter", urlPatterns = {"/*"})
public class DispatcherFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;

        // 设置请求对象的编码
        request.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 设置响应编码
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());

        String uri = req.getRequestURI();

        int lastIndex = uri.lastIndexOf("/");
        String action = uri.substring(lastIndex + 1);
        if (action.equals("product_input")) {
            /// //
        } else if (action.equals("product_save")) {
            ProductForm productForm = new ProductForm();
            productForm.setName(request.getParameter("name"));
            productForm.setDescription(request.getParameter("description"));
            productForm.setPrice(request.getParameter("price"));

            Product product = new Product();
            product.setName(productForm.getName());
            product.setDescription(productForm.getDescription());
            try {
                product.setPrice(Float.parseFloat(productForm.getPrice()));
            } catch (NumberFormatException e) {
                /// //
            }

            SaveProductAction saveProductAction = new SaveProductAction();
            saveProductAction.save(product);

            request.setAttribute("product", product);
        }

        String dispatchUrl = null;
        if (action.equals("product_input")) {
            dispatchUrl = "/jsp/ProductForm.jsp";
        } else if (action.equals("product_save")) {
            dispatchUrl = "/jsp/ProductDetails.jsp";
        }

        if (dispatchUrl != null) {
            RequestDispatcher requestDispatcher = request.getRequestDispatcher(dispatchUrl);
            requestDispatcher.forward(request, response);
        } else {
            chain.doFilter(request, response);
        }
    }

}
